/**
 * Copyright (C) 2016 Eshore Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.eshore.thrpc.heartbeat;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.thrift.TServiceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eshore.thrpc.common.ServerNode;
import com.eshore.thrpc.monitor.NamedThreadFactory;

/**
 * heartbeat管理器
 * <p>
 * 
 * @author : dsfan
 * @date : 2015-6-17
 */
public class HeartBeatManager<T> {

    /** LOGGER */
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());

    /** {@link ScheduledExecutorService} */
    private final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1,
            new NamedThreadFactory("Server-Heartbeat", true));

    /** 心跳定时器 */
    private ScheduledFuture<?> heatbeatTimer;

    /** 心跳频率，毫秒。默认0，不会执行心跳。 */
    private final int initialDelay;


    /** 重试间隔 */
    private final int interval;

    private ServerNode serverNode;

    /** 连接池 */
    private final GenericKeyedObjectPool<ServerNode, TServiceClient> pool;

    /**
     * @param dynamicHostSet
     * @param heartbeat
     * @param heartbeatTimeout
     * @param times
     * @param interval
     * @param pool
     */
    public HeartBeatManager(int initialDelay, int interval,
            GenericKeyedObjectPool<ServerNode, TServiceClient> pool) {
        this.initialDelay = initialDelay;
        this.interval = interval;
        this.pool = pool;
    }

    /**
     * 启动heartbeat
     * <p>
     */
    public void startHeatbeatTimer() {
        stopHeartbeatTimer();
        heatbeatTimer =
                scheduled.scheduleWithFixedDelay(new HeartBeatTask<T>(serverNode, pool),
                        initialDelay, interval, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止heartbeat
     * <p>
     */
    public void stopHeartbeatTimer() {
        try {
            ScheduledFuture<?> timer = heatbeatTimer;
            if (timer != null && !timer.isCancelled()) {
                timer.cancel(true);
            }
        } catch (Throwable t) {
            LOGGER.warn(t.getMessage(), t);
        } finally {
            heatbeatTimer = null;
        }
    }

    public ServerNode getServerNode() {
        return serverNode;
    }

    public void setServerNode(ServerNode serverNode) {
        this.serverNode = serverNode;
    }

}
